package com.itheima.service.mongo.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.UserLike;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.mongo.UserLikeService;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.UserLikeCountVo;
import com.itheima.vo.UserLikeVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;


@Service
public class UserLikeServiceImpl implements UserLikeService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, Long likeUserId) {

        //1.先判断是否有该条记录
        Query query = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        boolean exists = mongoTemplate.exists(query, UserLike.class);

        //2.如果不存在,向UserLike表插入该条数据
        if(!exists){
            UserLike userLike = new UserLike();
            userLike.setCreated(System.currentTimeMillis());
            userLike.setUserId(userId);
            userLike.setLikeUserId(likeUserId);
            mongoTemplate.save(userLike);
        }


    }

    @Override
    public boolean isMutualLike(Long userId, Long likeUserId) {
        //1.你是否喜欢了ta(查询user_like表中的数据)
        Query query1 = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        boolean exists1 = mongoTemplate.exists(query1, UserLike.class);

        //2.ta是否喜欢了你
        Query query2 = new Query(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId));
        boolean exists2 = mongoTemplate.exists(query2, UserLike.class);

        //返回与结果
        return exists1 && exists2;
    }

    @Override
    public void delete(Long userId, Long likeUserId) {
        //1.先判断是否有该条记录
        Query query = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        boolean exists = mongoTemplate.exists(query, UserLike.class);
        if(exists){
            //如果存在，删除
            mongoTemplate.remove(query,UserLike.class);
        }
    }

    @Override
    public UserLikeCountVo findUserCounts(Long userId) {
        //- 相互喜欢: 查询好友列表 (从friend表中根据userId查询我的所有好友数量  )
        Query query1 = new Query(Criteria.where("userId").is(userId));
        long eachLoveCount = mongoTemplate.count(query1, Friend.class);

        //- 喜欢: 查询你喜欢的用户 (  从user_like表中根据userId查询所有我喜欢的用户数量  )
        Query query2 = new Query(Criteria.where("userId").is(userId));
        long loveCount = mongoTemplate.count(query2, UserLike.class);

        //- 粉丝: 查询别人喜欢你的用户 (  从user_like表中根据likeUserId查询所有喜欢我的用户数量 )
        Query query3 = new Query(Criteria.where("likeUserId").is(userId));
        long fanCount = mongoTemplate.count(query3, UserLike.class);

        //封装UserLikeCountVo
        return new UserLikeCountVo(eachLoveCount,loveCount,fanCount);
    }

    @Override
    public PageBeanVo findUserList(Long userId, Integer type, Integer pageNum, Integer pageSize) {

        if(type == 1){
            //- 相互喜欢: 查询好友列表 (从friend表中根据userId分页查询我的好友  )
            //查询我的好友
            Query query = new Query(Criteria.where("userId").is(userId)).skip((pageNum - 1) * pageSize).limit(pageSize);
            List<Friend> friendList = mongoTemplate.find(query, Friend.class);
            long count = mongoTemplate.count(query, Friend.class);
            List<UserLikeVo> userLikeVoList = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(friendList)){
                for (Friend friend : friendList) {
                    //获取好友id
                    Long friendId = friend.getFriendId();
                    //获取两个人的缘分值
                    Integer score = getScore(userId, friendId);

                    UserLikeVo userLikeVo = new UserLikeVo();
                    userLikeVo.setId(friendId);
                    userLikeVo.setMatchRate(score);

                    userLikeVoList.add(userLikeVo);
                }
            }
            return new PageBeanVo(pageNum,pageSize,count,userLikeVoList);
        }else if(type == 2){
            //- 喜欢: 查询你喜欢的用户 (从user_like表中根据userId分页查询我喜欢的用户  )
            Query query = new Query(Criteria.where("userId").is(userId)).skip((pageNum - 1) * pageSize).limit(pageSize);
            List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
            long count = mongoTemplate.count(query, UserLike.class);
            List<UserLikeVo> userLikeVoList = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(userLikeList)){
                for (UserLike userLike : userLikeList) {
                    //获取喜欢的用户id
                    Long likeUserId = userLike.getLikeUserId();
                    //获取两个人的缘分值
                    Integer score = getScore(userId, likeUserId);

                    UserLikeVo userLikeVo = new UserLikeVo();
                    userLikeVo.setId(likeUserId);
                    userLikeVo.setMatchRate(score);

                    userLikeVoList.add(userLikeVo);
                }
            }
            return new PageBeanVo(pageNum,pageSize,count,userLikeVoList);
        }else  if (type == 3){
            //- 粉丝: 查询别人喜欢你的用户 (  从user_like表中根据likeUserId分页查询喜欢我的用户 )
            Query query = new Query(Criteria.where("likeUserId").is(userId)).skip((pageNum - 1) * pageSize).limit(pageSize);
            List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
            long count = mongoTemplate.count(query, UserLike.class);
            List<UserLikeVo> userLikeVoList = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(userLikeList)){
                for (UserLike userLike : userLikeList) {
                    //获取喜欢的用户id
                    Long otherUserId = userLike.getUserId();
                    //获取两个人的缘分值
                    Integer score = getScore(userId, otherUserId);

                    UserLikeVo userLikeVo = new UserLikeVo();
                    userLikeVo.setId(otherUserId);
                    userLikeVo.setMatchRate(score);
                    //当粉丝也已经喜欢你之后,这个标识设置为true
                    if (isMutualLike(userId,otherUserId)){
                        userLikeVo.setAlreadyLove(true);
                    }
                    userLikeVoList.add(userLikeVo);
                }
            }
            return new PageBeanVo(pageNum,pageSize,count,userLikeVoList);
        }else {
            //- 谁看过我: 查询访客列表( 从visitor表中根据userId分页查询访问过的用户)
            Query query = new Query(Criteria.where("userId").is(userId)).skip((pageNum - 1) * pageSize).limit(pageSize);
            List<Visitor> visitorList = mongoTemplate.find(query, Visitor.class);
            long count = mongoTemplate.count(query, Visitor.class);
            List<UserLikeVo> userLikeVoList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(visitorList)) {
                for (Visitor visitor : visitorList) {
                    //获取到好友的id
                    Long friendId = visitor.getVisitorUserId();

                    //获取两人的缘分值
                    Integer score = getScore(userId, friendId);

                    // 创建vo
                    UserLikeVo userLikeVo = new UserLikeVo();
                    userLikeVo.setId(friendId);
                    userLikeVo.setMatchRate(score);

                    // 放入临时集合
                    userLikeVoList.add(userLikeVo);
                }
            }
            return new PageBeanVo(pageNum,pageSize,count,userLikeVoList);
        }

    }


    //查询两个人的缘分值
    private Integer getScore(Long userId, Long friendId){
        Query query = new Query(Criteria.where("userId").is(friendId).and("toUserId").is(userId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if(recommendUser == null){
            return 99;
        }
        return recommendUser.getScore().intValue();//转为int类型
    }
}
